import whisper
from datetime import datetime
import os
from tempfile import NamedTemporaryFile

def transcribe_to_srt(audio_path: str, config) -> str:
    try:
        model = whisper.load_model(config.model_size)
        result = model.transcribe(audio_path, task='translate' if config.target_language != 'en' else 'transcribe')
        
        with NamedTemporaryFile(suffix=".srt", delete=False) as temp_file:
            srt_path = temp_file.name
            
            with open(srt_path, 'w', encoding='utf-8') as f:
                for i, segment in enumerate(result['segments'], 1):
                    start = datetime.fromtimestamp(segment['start']).strftime('%H:%M:%S,%f')[:-3]
                    end = datetime.fromtimestamp(segment['end']).strftime('%H:%M:%S,%f')[:-3]
                    f.write(f"{i}\n{start} --> {end}\n{segment['text'].strip()}\n\n")
            
            return srt_path
        
    except Exception as e:
        os.remove(audio_path)
        raise RuntimeError(f"语音转写失败: {str(e)}")